package xhg.com.resell.base.httpbase;

import android.net.ParseException;

import com.google.gson.JsonParseException;

import org.json.JSONException;

import java.net.ConnectException;
import java.net.SocketException;
import java.net.UnknownHostException;

import javax.net.ssl.SSLException;

import retrofit2.HttpException;

/**
 * @author lew1210
 * 对本地产生的exception进行处理
 */
public class CustomException {
    /**
     * 未知错误
     */
    public static final int UNKNOWN = 1000;

    /**
     * 解析错误
     */
    public static final int PARSE_ERROR = 1001;

    /**
     * 网络错误
     */
    public static final int NETWORK_ERROR = 1002;

    /**
     * 协议错误
     */
    public static final int HTTP_ERROR = 1003;

    /**
     * 证书错误
     */
    public static final int SSL_ERROR = 1005;




    /**
     * 对异常进行处理，封装
     */
    public static ApiException handleException(Throwable e) {
        ApiException ex = new ApiException(UNKNOWN, e.getMessage());

        if (e instanceof JsonParseException
                || e instanceof JSONException
                || e instanceof ParseException) {
            ex = new ApiException(PARSE_ERROR, e.getMessage());
        } else if (e instanceof ConnectException) {
            ex = new ApiException(NETWORK_ERROR, e.getMessage());
        } else if (e instanceof UnknownHostException || e instanceof SocketException) {
            ex = new ApiException(NETWORK_ERROR, e.getMessage());
        } else if (e instanceof HttpException) {
            ex = new ApiException(HTTP_ERROR, e.getMessage());
        } else if (e instanceof SSLException) {
            ex = new ApiException(SSL_ERROR, e.getMessage());
        } else if (e instanceof ApiException) {
            ex = (ApiException) e;
        }

        return ex;
    }
}
